import http from './request.js';

class PostNotice {
    constructor() {
        this.isEditMode = false;
        this.postId = null;
        this.titleInput = document.querySelector('.post-title');
        this.contentInput = document.querySelector('.post-content');
        this.categorySelect = document.querySelector('.category-select');
        this.fileInput = document.getElementById('fileInput');
        this.selectedFiles = document.getElementById('selectedFiles');
        this.postBtn = document.querySelector('.post-btn');
        this.cancelBtn = document.querySelector('.cancel-btn');
        this.selectedFileList = [];
        
        this.init();
    }

    async init() {
        // 检查是否是编辑模式
        const urlParams = new URLSearchParams(window.location.search);
        this.isEditMode = urlParams.get('edit') === 'true';
        this.postId = urlParams.get('id');

        // 更新页面标题
        const header = document.querySelector('app-header');
        if (header) {
            header.setAttribute('page-title', this.isEditMode ? 'Edit Post' : 'Create Post');
        }

        // 加���标签选项
        await this.loadTags();

        if (this.isEditMode && this.postId) {
            await this.loadPostData();
        }

        this.bindEvents();
    }

    async loadTags() {
        try {
            const tags = await http.get('/tags', { type: 1 }); // type=1 表示帖子标签
            this.categorySelect.innerHTML = `
                <option value="">Select Category</option>
                ${tags.map(tag => `
                    <option value="${tag.TagID}">${tag.Name}</option>
                `).join('')}
            `;
        } catch (error) {
            console.error('Failed to load tags:', error);
            alert('Failed to load categories');
        }
    }

    async loadPostData() {
        try {
            const post = await http.get(`/posts/${this.postId}`);
            
            // 填充表单
            this.titleInput.value = post.Title;
            this.contentInput.value = post.Content;
            this.categorySelect.value = post.TagID;

            // 处理多个媒体文件
            if (post.Media) {
                const mediaFiles = post.Media.split(',');
                this.selectedFileList = mediaFiles.map(path => ({
                    name: path.split('/').pop(),
                    isExisting: true,
                    path: path
                }));
                this.renderFileList(this.selectedFileList);
            }

            this.postBtn.textContent = 'Save';
        } catch (error) {
            console.error('Failed to load post:', error);
            alert('Failed to load post data');
        }
    }

    bindEvents() {
        this.postBtn.addEventListener('click', () => this.handleSubmit());
        this.cancelBtn.addEventListener('click', () => this.handleCancel());
        this.fileInput.addEventListener('change', (e) => this.handleFileSelect(e));
    }

    async handleSubmit() {
        const title = this.titleInput.value.trim();
        const content = this.contentInput.value.trim();
        const tagId = this.categorySelect.value;

        if (!title || !content || !tagId) {
            alert('Please fill in all required fields');
            return;
        }

        try {
            // 处理多个文件上传
            let mediaPaths = [];
            const newFiles = this.selectedFileList.filter(file => !file.isExisting);
            
            // 保留现有文件的路径
            const existingFiles = this.selectedFileList
                .filter(file => file.isExisting)
                .map(file => file.path);
            mediaPaths.push(...existingFiles);

            // 上传新文件
            for (const file of newFiles) {
                const formData = new FormData();
                formData.append('file', file);
                const uploadResult = await http.post('/upload', formData);
                mediaPaths.push(uploadResult.url);
            }

            // 准备帖子数据
            const postData = {
                title,
                content,
                tagId: parseInt(tagId),
                media: mediaPaths.join(',') // 使用逗号分隔多个文件路径
            };

            if (this.isEditMode) {
                await http.put(`/posts/${this.postId}`, postData);
                alert('Post updated successfully');
                window.location.href = `./notice-detail.html?id=${this.postId}`;
            } else {
                const response = await http.post('/posts', postData);
                alert('Post created successfully');
                window.location.href = './index.html';
            }
        } catch (error) {
            console.error('Failed to submit post:', error);
            alert('Failed to submit post: ' + error.message);
        }
    }

    handleCancel() {
        if (this.isEditMode) {
            window.location.href = `./notice-detail.html?id=${this.postId}`;
        } else {
            window.location.href = './index.html';
        }
    }

    handleFileSelect(e) {
        const files = Array.from(e.target.files);
        // 追加新选择的文件
        this.selectedFileList = [...this.selectedFileList, ...files];
        this.renderFileList(this.selectedFileList);
    }

    renderFileList(files) {
        this.selectedFiles.innerHTML = files.map((file, index) => `
            <div class="file-item">
                <span class="file-name">${file.name}</span>
                <button class="remove-file" onclick="postNotice.removeFile(${index})">×</button>
            </div>
        `).join('');
    }

    removeFile(index) {
        this.selectedFileList.splice(index, 1);
        this.renderFileList(this.selectedFileList);
    }
}

// 创建全局实例
window.postNotice = new PostNotice(); 